package com.bawei.demo_shoppingcar.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by HP on 2017/3/16.
 */

public class HttpUtils {


    private String json;

    public static String readUrl(String string) {
        String json = "";
        try {
            URL url = new URL(string);
            HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
            openConnection.setReadTimeout(3000);
            openConnection.setConnectTimeout(2000);
            int responseCode = openConnection.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = openConnection.getInputStream();
                json =   InsertToStr(inputStream);
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  json ;
    }

    public static String InsertToStr(InputStream inputStream) {
        String json = "";
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            json = output.toString("utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

}
